JavaScript syntax
part 13/59 · 107.4 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Note: undefined is considered a genuine primitive type. Unless explicitly converted, the undefined value may behave unexpectedly in comparison to other types that evaluate to false in a logical context.
let test; // variable declared, but not defined, ...
// ... set to value of undefined
const testObj = {};
console.log(test); // test variable exists, but value not ...
// ... defined, displays undefined
console.log(testObj.myProp); // testObj exists, property does not, ...
// ... displays undefined
console.log(undefined == null); // unenforced type during check, displays true
console.log(undefined === null); // enforce type during check, displays false
Note: There is no built-in language literal for undefined. Thus (x === undefined) is not a foolproof way to check whether a variable is undefined, because in versions before ECMAScript 5, it is legal for someone to write var undefined = "I'm defined now";. A more robust approach is to compare using (typeof x === 'undefined').
Functions like this will not work as expected:
function isUndefined(x) { let u; return x === u; } // like this...
function isUndefined(x) { return x === void 0; } // ... or that second one
function isUndefined(x) { return (typeof x) === "undefined"; } // ... or that third one
Here, calling isUndefined(my_var) raises a ReferenceError if my_var is an unknown identifier, whereas typeof my_var === 'undefined' does not.
Number